package com.jiaai.controller;

import com.jiaai.util.UploadUtil;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;

import java.util.Iterator;
/**
 * 文件上传
 */

@RestController
public class UploadController {
    /**
     * 上传日志文件
     * @param application
     * @param request
     * @return
     */
    @RequestMapping("/upload/logs/{application}")
    public  Object uploadLogs(
            @PathVariable("application") String application,
            HttpServletRequest request){
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        StringBuffer files=new StringBuffer();
        //判断 request 是否有文件上传,即多部分请求
        if(multipartResolver.isMultipart(request)){
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            //取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while(iter.hasNext()){
                String key=iter.next();
                //取得上传文件
                MultipartFile file = multiRequest.getFile(key);
                String fileName= UploadUtil.copyFile(file,application,"logs");
                files.append( UploadUtil.getHttpUrl(fileName,application,"logs")+",");
            }
        }
        return   files.toString();
    }
     @RequestMapping("/upload/{application}/{directories}")
     public  Object upload(
                          @PathVariable("application") String application,
                          @PathVariable(value = "directories",required = false)String  directories,
                          HttpServletRequest request){
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        StringBuffer files=new StringBuffer();
        //判断 request 是否有文件上传,即多部分请求
        if(multipartResolver.isMultipart(request)){
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            //取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while(iter.hasNext()){
                String key=iter.next();
                //取得上传文件
                MultipartFile file = multiRequest.getFile(key);
                String fileName= UploadUtil.copyFile(file,application,directories);
                files.append( UploadUtil.getHttpUrl(fileName,application,directories)+",");


            }

        }
        return   files.toString();
    }

}
